import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../provider/_providers.dart';
import '../../provider/chatdetailprovider.dart';


class ChatdetailMessagesUi extends ConsumerWidget {

  ChatdetailMessagesUi({super.key,required this.chatDetailProvider});

  ChangeNotifierProvider<ChatDetailProvider> chatDetailProvider;

  /*
  List<ChatMessage> messages = [
    ChatMessage(messageContent: "Hello, Will", messageType: "receiver"),
    ChatMessage(messageContent: "How have you been?", messageType: "receiver"),
    ChatMessage(
        messageContent: "Hey Kriss, I am doing fine dude. wbu?",
        messageType: "sender"),
    ChatMessage(messageContent: "ehhhh, doing OK.", messageType: "receiver"),
    ChatMessage(
        messageContent: "Is there any thing wrong?", messageType: "sender"),
  ];
  */



  final ScrollController _scroll = ScrollController();

  void _scrollDown() {
    if (_scroll.hasClients) {
      final position = _scroll.position.maxScrollExtent;
      _scroll.jumpTo(position);
      print("_scroll");
      print(position);
    }
  }


  @override
  Widget build(BuildContext context, WidgetRef ref) {

    return Consumer(
        builder: (context, ref, child)
    {

      ref.watch(chatDetailProvider);

      var messages = ref.read(chatDetailProvider).messages;
      // 延时1s执行返回
      Future.delayed(Duration(milliseconds: 250), (){
        _scrollDown();
        print('延时1s执行');
      });



      return Container(

          padding: EdgeInsets.only(top: 10, bottom: 100),
          child: ListView.builder(
            itemCount: messages.length,
            shrinkWrap: true,

            controller: _scroll,
            padding: EdgeInsets.only(top: 5, bottom: 5),
            physics: AlwaysScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              return Container(
                padding: EdgeInsets.only(
                    left: 14, right: 14, top: 10, bottom: 10),
                child: Align(
                  alignment: (messages[index]
                      .messageType ==
                      "receiver"
                      ? Alignment.topLeft
                      : Alignment.topRight),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      color: (messages[index]
                          .messageType == "receiver"
                          ? Colors.grey.shade200
                          : Colors.blue[200]),
                    ),
                    padding: EdgeInsets.all(16),
                    child: Text(
                      messages[index].messageContent,
                      style: TextStyle(fontSize: 15),
                    ),
                  ),
                ),
              );
            },
          ));
    });


  }
}
